package com.lyf.security.login.interceptor;

import com.lyf.security.login.annotaion.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @AUTHOR LYF
 * @DATE 2022/1/21
 * @VERSION 1.0
 * @DESC
 */
@Configuration
public class AuthenticInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断访问该页面有无权限
        // 解析访问的URL，看此Method上的注解看需要何种权限，在Redis中进行查询是否有该权限（遍历权限列表）
        // 可通过handler进行判断请求得何种Method
//        request.ge
        System.out.println("认证拦截...");
        String token = request.getHeader("token");
        String username = (String) redisTemplate.opsForValue().get("token:"+token);//map:key为token，value为username
        if(this.hasPermission(username,handler)){
            return true;
        }
        // 通过PrintWriter进行反馈NoPermission
        response.getWriter().write("No Permission!");
        return false;
    }
    boolean hasPermission(String username,Object handler){
        if(handler instanceof HandlerMethod){
           HandlerMethod handlerMethod = (HandlerMethod) handler;
//           handlerMethod.getMethodAnnotation(RequiredPermission.class);
//           RequiredPermission requiredPermission = handlerMethod.
//                   getMethod().getAnnotation(RequiredPermission.class);
            RequiredPermission requiredPermission = handlerMethod.getMethod().getDeclaredAnnotation(RequiredPermission.class);
            System.out.println("requireP1:"+requiredPermission+(requiredPermission==null?"":requiredPermission.value()));
            requiredPermission = handlerMethod.getMethod().getAnnotation(RequiredPermission.class);
            System.out.println("requireP2:"+requiredPermission+(requiredPermission==null?"":requiredPermission.value()));
            // 还需要考虑类的注解...
            if(requiredPermission==null)
                requiredPermission = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequiredPermission.class);

           //System.out.println("permission:"+requiredPermission.value());
           if(requiredPermission==null)
               return true;//注解为空,则直接放行
            // 遍历权限列表，看是否具有该权限
            String permissionListKey = "userPermissionList:"+username;
            long keySize = redisTemplate.opsForList().size(permissionListKey);
            List<String> permissionList = redisTemplate.opsForList()
                    .range(permissionListKey,0,keySize);
            for(String str:permissionList){
                if(str.equals(requiredPermission.value())){
                    return true;
                }
            }
            return false;
        }
        return false;
    }
}
